package net.sf.jgcs.utils;

import net.sf.jgcs.ControlListener;
import net.sf.jgcs.ControlSession;
import net.sf.jgcs.adapters.ExtendedControlListener;
import net.sf.jgcs.adapters.ExtendedMembershipListener;
import net.sf.jgcs.membership.MembershipListener;
import net.sf.jgcs.membership.MembershipSession;

public class ControlSessionUtil {
	
	public static void redefineControlListener(ControlSession controlSession, ControlListener newListener){
		ControlListener currentControlListener = controlSession.getControlListener();
		if(currentControlListener == null){
			controlSession.setControlListener(newListener);
		}
		else if(currentControlListener instanceof ExtendedControlListener){
			((ExtendedControlListener)currentControlListener).add(newListener);
		}
		else{
			ExtendedControlListener extendedControlListener = new ExtendedControlListener();
			extendedControlListener.add(currentControlListener);
			extendedControlListener.add(newListener);
			controlSession.setControlListener(extendedControlListener);
		}
	}
	
	public static void redefineMembershipListener(MembershipSession membershipSession, MembershipListener newListener){
		MembershipListener currentMembershipListener = membershipSession.getMembershipListener();
		if(currentMembershipListener == null){
			membershipSession.setMembershipListener(newListener);
		}
		else if(currentMembershipListener instanceof ExtendedMembershipListener){
			((ExtendedMembershipListener)currentMembershipListener).add(newListener);
		}
		else{
			ExtendedMembershipListener extendedMembershipListener = new ExtendedMembershipListener();
			extendedMembershipListener.add(currentMembershipListener);
			extendedMembershipListener.add(newListener);
			membershipSession.setMembershipListener(extendedMembershipListener);
		}
	}

}
